package edu.xzit.controller;

import edu.xzit.exception.RunException;
import edu.xzit.entity.User;
import edu.xzit.service.UserService;
import edu.xzit.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "登录")
@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @ApiOperation(value = "登录接口")
    @GetMapping("/user/login")
    public Map<String, Object> login(User user) {
        log.info("用户名: [{}]", user.getName());
        log.info("密码: [{}]", user.getPwd());
        Map<String, Object> map = new HashMap<>();
        try {
            User userDB = userService.login(user);
            Map<String, Object> payload = new HashMap<>();
            payload.put("id", userDB.getId());
            payload.put("name", userDB.getName());
            //生成JWT的令牌
            String token = JWTUtils.getToken(payload);
            map.put("state", true);
            map.put("msg", "认证成功");
            map.put("token", token);//响应token
        } catch (Exception e) {
            map.put("state", false);
            map.put("msg", e.getMessage());
        }
        return map;
    }

    @ApiOperation(value = "测试接口")
    @PostMapping("/user/test")
    public Map<String, Object> test(HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<>();

        String token = request.getHeader("token");
        try {
            Claims claims = JWTUtils.parseJwt(token);
            log.info("用户id: [{}]", claims.get("id"));
            log.info("用户name: [{}]", claims.get("name"));
            map.put("state", true);
            map.put("msg", "请求成功!");
        } catch (RunException e) {
            map.put("state", false);
            map.put("msg", e.getMessage());
        }
        //处理自己业务逻辑
        return map;
    }


}
